import React from 'react';
import { history } from 'umi';
import { Menu, Button } from 'antd';
import routeConfig from '../routes';
import './index.less';

const { SubMenu } = Menu;

class Layout extends React.Component {
    state = {
        current: '',
    };

    handleClick = (e) => {
        this.props.history.push(e.key);
        this.setState({ current: e.key });
    };

    rendItem = (routes) => {
        if (!routes) return;
        return routes.map((route) => {
            if (route.routes) {
                return (
                    <SubMenu key={route.path} title={route.name}>
                        {this.rendItem(route.routes)}
                    </SubMenu>
                );
            } else {
                return <Menu.Item key={route.path}>{route.name}</Menu.Item>;
            }
        });
    };

    componentDidUpdate(preProps, preState) {
        if (this.state.current != location.pathname) {
            this.setState({ current: location.pathname });
        }
    }

    // find first route
    findForstRoute = (route) => {
        if (route.routes && route.routes.length) {
            return this.findForstRoute(route.routes[0]);
        }
        return route.path;
    };

    render() {
        if (location.pathname == '/') {
            const firstRoute = this.findForstRoute(routeConfig[0]);
            history.push(firstRoute);
        }

        return (
            <div className="app-container">
                <Menu
                    theme="dark"
                    onClick={this.handleClick}
                    selectedKeys={[this.state.current]}
                    mode="horizontal"
                >
                    {this.rendItem(routeConfig[0].routes)}
                </Menu>
                {this.props.children}
            </div>
        );
    }
}
export default Layout;
